<template>
  <div style="padding: 5px; border: 1px solid #ccc!important;">
    <iframe :src="src" style="width:100%;height:100%"></iframe>
  </div>
</template>

<script>
  import {
    defineComponent,
    watch,
    ref
  } from 'vue'
  
  import config from '../config/index.js'

  export default defineComponent({
    name: 'el-doc-runcode',
    inheritAttrs: false,
    props: {
      code: {
        type: Object,
        default: () => {
          return {
            id: 1,
            js: '',
            template: '',
            style: ''
          }
        }
      },
      reload: Boolean
    },
    setup (props) {

      const src = ref('')
 
      // 用 Window 传递代码
      if (!window.__code) {
        window.__code = {}
      }

      // 重新加载代码
      watch(() => props.reload, () => {
        const id = props.code.id
        window.__code[id] = props.code
        src.value = `${config.baseUrl}runcode/index.html?id=${id}&rnd=${new Date().valueOf()}`
      }, {immediate: true})
      
      return {
        src
      }
    }
  })
</script>